package com.atguigu.gulimall.search.service.impl;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.constant.ElasticConstant;
import com.atguigu.gulimall.search.service.ElasticSaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author: jianPing
 * @date: 2022/3/2 15:30
 * @description:
 */
@Service
public class ElasticSaveServiceImpl implements ElasticSaveService {
    @Autowired
    ElasticsearchClient client;

    @Override
    public boolean saveSkuEsModels(List<SkuEsModel> skuEsModels) throws IOException {
        List<BulkOperation> bulkOperationList = new ArrayList<>();

        for (SkuEsModel esModel : skuEsModels) {
            bulkOperationList.add(new BulkOperation.Builder().create(e -> e.document(esModel)).build());
        }

        BulkResponse bulkResponse = client.bulk(bulkRequest ->
                bulkRequest.index(ElasticConstant.productIndex).operations(bulkOperationList)
        );
        return bulkResponse.errors();

    }
}
